import { queryVehicle, deleteVehicle } from '../../services/vehicle'
import Toast from '@vant/weapp/toast/toast';
import Dialog from '@vant/weapp/dialog/dialog';
import { checkIfLogin } from '../../utils/check'

Page({
  /**
   * 页面的初始数据
   */
  data: {
    selectIndexList:[],
    isManage:false,
    currentItem:{
      // license:'苏A66666',
      // type:'兰博基尼',
    },
    vehicleList:[]
  },

  // onLoad(){
  //   console.log("进入我的车辆页面了~")
  //   this.getVehicleList()
  // },

  onShow(){
    checkIfLogin()
    this.getVehicleList()
  },

  async getVehicleList(){
    let vehicleRes = await queryVehicle()
    console.log("vehicleRes>>>", vehicleRes)
    if(vehicleRes.code === 200){
      this.setData({
        vehicleList: vehicleRes.rows
      })
    }
  },

  transManage(){
    this.setData({
      selectIndexList:[],
      isManage: true
    })
  },

  cancelManage(){
    this.setData({
      isManage: false,
    })
  },

  handleClick(event){
    let currentItem = event.currentTarget.dataset.currentitem
    let currentId = currentItem.id    
    if(!this.data.isManage){
      wx.navigateTo({
        url: `/pages/maintain-vehicle/maintain-vehicle?currentId=${currentId}`,
      })  
    }else{
      const tempSelectedList = this.data.selectIndexList
      let selectIdIndex = tempSelectedList.indexOf(currentId)
      if(selectIdIndex > -1){
        tempSelectedList.splice(selectIdIndex, 1)
      }else{
        tempSelectedList.push(currentId)
      }
      console.log("tempSelectedList>>>",tempSelectedList)
      this.setData({
        selectIndexList:tempSelectedList
      })
    }
  },

  handleAddVehicle(){
    wx.navigateTo({
      url: '/pages/maintain-vehicle/maintain-vehicle',
    }) 
    this.setData({
      isManage: false,
      selectIndexList:[]
    })
  },

  handleDeleteVehicle(){
    if(!this.data.selectIndexList.length){
      Toast.fail('请先选择车辆!');
      return
    }
    const delIds = this.data.selectIndexList.join(',')
    Dialog.confirm({
      title: '',
      message: '确认是否删除所选车辆?',
    })
    .then(() => {
      deleteVehicle(delIds).then(delRes => {
        if(delRes.code === 200){
          Toast.success('删除成功!');
          this.getVehicleList()
          this.setData({
            isManage: false,
          })
        }
      })
    })
    .catch(() => {
      // on cancel
    });
  },

  handleAllSelect(){
    let selectIndexList = this.data.selectIndexList
    let vehicleList = this.data.vehicleList

    if(selectIndexList.length < vehicleList.length){
      selectIndexList = []
      vehicleList.forEach(item => {
        selectIndexList.push(item.id)
      })
    }else {
      selectIndexList = []
    }
    this.setData({
      selectIndexList
    })
  }
})